﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class T9Helper
    {
        public static char lastInput { get; set; }

        public static Dictionary<string, char> dictionary
        {
            get { 
                return T9Repository.getDictionary();
            }
        }

        public static string getLetterCode(Dictionary<string, char> dic, char letter)
        {
            KeyValuePair<string, char> item = dic.Where(d => d.Key.Contains(letter)).FirstOrDefault();
            int letterIndex = item.Key.IndexOf(letter) + 1;
            char tempLetterCode = item.Value;
            string finalLetterCode = new String(tempLetterCode, letterIndex);

            if (isSameButtonOfLastInput(letter) || isSameLetterOfLastInput(letter))
                finalLetterCode = String.Concat(" ", finalLetterCode);

            lastInput = letter;
            return finalLetterCode;
        }

        public static bool isSameLetterOfLastInput(char letter)
        {
            if (letter == lastInput)
                return true;
            else
                return false;
        }

        public static bool isSameButtonOfLastInput(char letter)
        {
            KeyValuePair<string, char> item = dictionary.Where(d => d.Key.Contains(letter)).FirstOrDefault();

            if (item.Key.Contains(lastInput))
                return true;
            else
                return false;
        }

        public static string translateString(string s)
        {
            StringBuilder sb = new StringBuilder();

            foreach (char c in s)
            {
                sb.Append(getLetterCode(dictionary, c));
            }

            return sb.ToString();
        }

    }
}
